<?php

namespace App\Http\Controllers\Backend;

use App\Http\Requests\Role\AssignRequest;
use App\Http\Requests\Role\StoreRequest;
use App\Http\Requests\Role\UpdateRequest;
use App\Http\Responses\Role\PermissionResponse;
use App\Http\Responses\Role\IndexResponse;
use App\Http\Responses\Role\ShowResponse;
use App\Http\Controllers\Controller;
use App\Services\RoleService;

/**
 * 角色控制器
 *
 * Class RoleController
 * @package App\Http\Controllers\Backend
 */
class RoleController extends Controller
{
    protected $roleService;

    public function __construct(RoleService $roleService)
    {
        $this->roleService = $roleService;
    }

    /**
    * Display a listing of the resource.
    *
    * @return \Illuminate\Contracts\Support\Responsable
    */
    public function index()
    {
        $list = $this->roleService->getRoles();

        return new IndexResponse($list);
    }

    /**
    * Store a newly created resource in storage.
    *
    * @param  \Illuminate\Http\Request  $request
    * @return \Illuminate\Http\Response
    */
    public function store(StoreRequest $request)
    {
        $data = $request->validated();

        return response_api($this->roleService->storeRole($data));
    }

    /**
    * Display the specified resource.
    *
    * @param  int  $id
    * @return \Illuminate\Contracts\Support\Responsable
    */
    public function show($id)
    {
        $data = $this->roleService->getRole($id);

        return new ShowResponse($data);
    }

    /**
    * Update the specified resource in storage.
    *
    * @param  \Illuminate\Foundation\Http\FormRequest  $request
    * @param  int  $id
    * @return \Illuminate\Http\Response
    */
    public function update(UpdateRequest $request, $id)
    {
        $data = $request->validated();
        $bool = $this->roleService->updateRole($id, $data);

        return response_api($bool);
    }

    /**
    * Remove the specified resource from storage.
    *
    * @param  int  $id
    * @return \Illuminate\Http\Response
    */
    public function destroy($id)
    {
        $bool = $this->roleService->deleteRole($id);

        return response_api($bool);
    }

    /**
     * 给角色分配权限
     *
     * @param AssignRequest $request
     * @return array|\Illuminate\Http\JsonResponse
     */
    public function assign(AssignRequest $request)
    {
        $data = $request->validated();
        $result = $this->roleService->assignPermissionsToRole($data);

        return response_api($result);
    }

    public function getPermissionsByRoleId($id)
    {
        $rolePermissions = $this->roleService->findPermissionsByRoleId($id);

        return new PermissionResponse($rolePermissions);
    }
}
